#include "TiVoConnection.h"

using namespace MediaCenter;

TiVoConnection::TiVoConnection(boost::shared_ptr<boost::asio::io_service> io_service) :
    running(false),
	io_service(io_service)
{
	running = true;
    connectionThread = new boost::thread(boost::bind(&TiVoConnection::ConnectionThreadFunc, this));
}

TiVoConnection::~TiVoConnection()
{
	Shutdown();
}

void TiVoConnection::Shutdown()
{
    if (running)
    {
        running = false;
        connectionThread->join();
    }
}

bool TiVoConnection::IsConnected()
{
	return socket->is_open();
}

void TiVoConnection::SendCommand(const char* const Command)
{
	if (IsConnected())
	{
		boost::asio::write(*socket, boost::asio::buffer(Command, strlen(Command)));
	}
}

void TiVoConnection::ConnectionThreadFunc()
{
	char* host = "192.168.0.8";
	unsigned short port = 31339;
	std::ostringstream portStream;
	portStream << port;
    
	tcp::resolver resolver(*io_service);
	tcp::resolver::query query(host, portStream.str());
	tcp::resolver::iterator it = resolver.resolve(query);
	tcp::resolver::iterator end;

	socket = boost::shared_ptr<tcp::socket>(new tcp::socket(*io_service));

    while(running)
    {
		if (!socket->is_open())
		{
			boost::system::error_code error = boost::asio::error::host_not_found;
			while(error && it != end)
			{
				if(socket->is_open()) socket->close();
				socket->connect(*it++, error);
			}

			if (error)
			{
				printf("Unable to connect to TiVo.\n");
			}
			else
			{
				printf("Connected to TiVo.\n");
			}
		}

		boost::this_thread::sleep(boost::posix_time::milliseconds(5000));
    }

	if (IsConnected())
	{
		socket->close();
	}
}
